package com.pengtu.gsj.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pengtu.gsj.controller.base.BaseController;
import com.pengtu.gsj.dao.base.Page;
import com.pengtu.gsj.dao.base.QueryFilter;
import com.pengtu.gsj.dao.base.QueryFilter.MatchType;
import com.pengtu.gsj.entity.app.Organization;
import com.pengtu.gsj.entity.app.Sysmenu;
import com.pengtu.gsj.exception.ControllerException;
import com.pengtu.gsj.interceptor.Token;
import com.pengtu.gsj.service.system.OrganizationService;
import com.pengtu.gsj.service.system.SysmenuManagerService;
import com.pengtu.gsj.utils.LoadDataUtils;
import com.pengtu.gsj.utils.web.SpringMvcUtils;

/**
 * 
 * 
 * OrganizationController
 * 
 * 2017年4月18日 下午1:55:12
 * 
 * @version 1.0.0
 *
 */
@Controller
@RequestMapping("/organization/")
public class OrganizationController extends BaseController {

	@Autowired
	private OrganizationService organizationService;
	
	@Autowired
	private SysmenuManagerService sysmenuManagerService;
	
	
	/**
	 * 
	 * loadEntity:
	 * 适用: 每个方法执行之前都会执行该方法
	 * @param id  主键id
	 * @return 返回持久对象或者新创建对象
	 * @exception 
	 * @since  1.0.0
	 */
	@ModelAttribute
	public Organization loadEntity(String id,Model model){
		Organization organization ;
		if (StringUtils.isNotEmpty(id)) {
			organization = organizationService.getOrganization(id);
		}else {
			organization = new Organization();
		}
		model.addAttribute("top", SpringMvcUtils.getParameter("top"));
		model.addAttribute("left", SpringMvcUtils.getParameter("left"));
		return organization;
	}
	
	/**
	 * 
	 * getorganizationList:
	 * 适用:显示所有单位列表
	 * @param model 传递参数
	 * @return 返回到单位列表页面
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("list")
	public String getOrganizationList(Model model){
		List<Organization> list = Lists.newArrayList();
		String msg = SpringMvcUtils.getParameter("msg");
		if (StringUtils.isNotEmpty(msg)) {
			model.addAttribute("msg", msg);
		}
		QueryFilter queryFilter = new QueryFilter();
		List<String> values = new ArrayList<String>();
		values.add("1");
		values.add("2");
		queryFilter.addFilterList("type", values);
		List<Organization> sourcelist = organizationService.findOrganizations(queryFilter);
		Organization dj = organizationService.getTop();
		Organization.sortList(list, sourcelist, dj.getId());
		model.addAttribute("topId", dj.getId());
		model.addAttribute("list", list);
		return "system/organization";
	}
	
	@RequestMapping(value="listInfo", produces = "application/json; charset=utf-8")
	@ResponseBody
	public Page<Organization> getOrganization(Page<Organization> page, HttpServletRequest request){
		QueryFilter queryFilter = QueryFilter.buildFromHttpRequest(request);
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		page = organizationService.findOrganizations(page, queryFilter);
		return page;
	}
	
	/**
	 * 
	 * showOrInputorganizationInfo:
	 * 适用:新增和查看单位详情时会用到该方法
	 * @param id   单位主键id
	 * @param model  传递参数
	 * @return    返回单位详情页面
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("input")
	@Token(save = true)
	public String showOrInputOrganizationInfo(@ModelAttribute Organization organization, Model model){
		List<Sysmenu> menuList = sysmenuManagerService.getAll();
		model.addAttribute("menuList", menuList);
		String parentId = SpringMvcUtils.getParameter("parentId");
		if(StringUtils.isNotEmpty(parentId)){
			Organization parent = organizationService.getOrganization(parentId);
			organization.setParent(parent);
		}
		return "system/organization_input";
	}
	
	/**
	 * 
	 * saveOrganization:
	 * 适用:新增和修改单位信息时
	 * @param organization   接受单位属性信息对象
	 * @param model  传递对象
	 * @return  单位列表页面
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("save")
	@Token(remove = true)
	public String saveOrganization(@ModelAttribute Organization organization, RedirectAttributes attributes)throws Exception{
		organization.setParent(organizationService.get(organization.getParent().getId()));
		String oldParentIds = organization.getParentIds(); // 获取修改前的parentIds，用于更新子节点的parentIds
		organization.setParentIds(organization.getParent().getParentIds()+organization.getParent().getId()+",");
		organizationService.saveOrganization(organization);
		// 更新子节点 parentIds
		List<Organization> list = organizationService.getByParentIds(organization.getId());
		for (Organization e : list){
			e.setParentIds(e.getParentIds().replace(oldParentIds, organization.getParentIds()));
			organizationService.saveOrganization(e);
		}	
		
			attributes.addFlashAttribute("msg", "保存成功！");
			attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
			attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
		return "redirect:/organization/list.do";
	}
	
	
	/**
	 * 
	 * deleteOrganization:
	 * 适用:页面删除某个单位时
	 * @param id     单位主键id
	 * @param model  参数传递工具
	 * @return 返回到单位列表页面
	 * @throws Exception 异常统一处理
	 * @exception 抛出参数异常错误并跳转到相应页面
	 * @since  1.0.0
	 */
	@RequestMapping("delete")
	public String deleteOrganization(@ModelAttribute Organization organization,RedirectAttributes attributes){
		if (StringUtils.isEmpty(organization.getId())) {
			throw new ControllerException("参数id错误");
		}
		organizationService.deleteOrganization(organization.getId());
		attributes.addFlashAttribute("msg", "单位删除成功!");
		attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
		attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
		return "redirect:/organization/list.do";
	}
	
	/**
	 * 
	 * treeData:
	 * 适用:新增和修改单位信息
	 * @return 返回  json
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody
	@RequestMapping(value="treeData",produces = "application/json; charset=utf-8")
	public List<Map<String, Object>> treeData(){
		String extId = SpringMvcUtils.getParameter("extId");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Organization> oList = Lists.newArrayList();
		QueryFilter queryFilter = new QueryFilter();
		queryFilter.addFilter("type", "2", MatchType.EQ);
		oList = organizationService.findOrganizations(queryFilter);
		for (int i = 0; i < oList.size(); i++){
			Organization e = oList.get(i);
			if ((extId == null || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)) ){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParent()!=null?e.getParent().getId():0);
				map.put("name", e.getOrgName());
				mapList.add(map);
			}
		}
		return(mapList);
	}
	
	@ResponseBody
	@RequestMapping(value = "orgData")
	public List<Map<String, Object>> orgData(){
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Organization> oList = Lists.newArrayList();
		oList = LoadDataUtils.getMaintenanceOrg();
		for (Organization organization : oList) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", organization.getId());
			map.put("pId", organization.getParent()!=null?organization.getParent().getId():0);
			map.put("name", organization.getOrgName());
			mapList.add(map);
		}
		return(mapList);
	}
	
}
